import fetch from './fetch';
import * as domains from './env';
import * as Util from './utils';
import router from '@/router';
// import Vue from 'vue'

let store, client;

let lat, lng, cityCode, cityName, poiId, poiName, storeCode, storeLocation, storeName, areaId;
Window.wxObj = {
    title: '苏宁小店，一个会上网的小店', // 分享标题
    link: location.href, // 分享链接
    imgUrl: location.protocol + '//' + location.hostname + '/images/logo.jpg', // 分享图标
    desc: '商超宅配1小时达，生鲜果蔬每日好新鲜！'
};
/*let wxObj = {
    title: '苏宁小店，一个会上网的小店', // 分享标题
    link: location.href, // 分享链接
    imgUrl: location.protocol + '//' + location.hostname + '/images/logo.jpg', // 分享图标
    desc: '商超宅配1小时达，生鲜果蔬每日好新鲜！'
};*/

let resolve, reject;

/* 终端判断 */
function checkClient() {
    let ua = navigator.userAgent;

    client = {
        app: /-app/i.test(ua),
        weixin: /MicroMessenger/i.test(ua),
        ios: /(iPhone|iPod|iPad);?/i.test(ua),
        android: /android/i.test(ua)
    };

    store.commit('setClient', client);
}

/* 页面路由 */
function pageRouter() {
    $(document).on('click', 'a[href^="http://m.suning.com"]', function(e) {
        let href = $(this).attr('href');
        routeTo(href);
        e.preventDefault();
    });
}

/* 执行路由规则 */
function routeTo(href) {
    if (client.app) {
        return baseApi.pageRouter(href);
    }

    var search = href.substr(href.indexOf('?')),
        params = search.substr(1).split('&'),
        obj = {}, jumpTo = '';

    for (var i = 0; i < params.length; i++) {
        var parts = params[i].split('=');
        obj[parts[0]] = parts[1];
    }

    // 根据snstoreTypeCode确定跳转地址
    var p1 = obj['snstoreTypeCode'],
        p2 = obj['snstoreId'],
        p3 = obj['extId'];

    if (p1) {
        switch(p1) {
            case '1001': jumpTo = '/'; break;
            case '1002':
                if (/^1/ig.test(p3)) {
                    location.href = p2 + (p2.indexOf('?')>0 ? '&' : '?') + 'minicart=true';
                }
                else {
                    location.href = p2;
                }
                break;
            // case '1003': jumpTo = '/detail.html?cmmdtyCode=' + p2; break;
            case '1003': 
                let a = p2.splice('_');
                jumpTo = `/detail/${a[0]}/${a[1]}`; break;
            //case '1004': jumpTo = '/'; break;
            case '1005': jumpTo = '/coupon/store'; break;
            case '1006': jumpTo = '/orders'; break;
            case '1007': 
                location.href = 'http://s.suning.com/report/custom/m/cmws.htm';
                break;
            case '1008':
                if (!p2) {
                    jumpTo = '/list';
                    break;
                }
                if (p3 == '1') {
                    jumpTo = `/shoplist/${p2}`;
                    break;
                }
                if (p3 == '0') {
                    jumpTo = '/list';
                    break;
                }
                break;
            case '1009': jumpTo = '/cart1'; break;
            case '1010': jumpTo = '/my'; break;
            // default:
            //     return !$('<div class="apptip"><div class="apptip-main"><a href="' + domains.xd + '/dlapp/jump.html" class="btn"></a><a href="javascript:void(0);" class="close"></a></div></div>')
            //         .appendTo('body')
            //         .on('click', '.close', function() {
            //             $('.apptip').remove();
            //         });

        }
        router.push(jumpTo)
        // location.href = jumpTo;
    }
}

/* 配置passport */
function setPassport() {
    window.passport_config = window.passport_config || {
        base: domains.tps + '/',
        loginTheme: "wap_new"
    };
}


/* 微信端初始化 */
function initWeixin(callback) {
    // 调用微信认证接口
    $.ajax({
        url: '//act.suning.com/act-wap-web/wap/public/getWechatToken.htm?url=' + encodeURIComponent(window.location.href.split('#')[0]),
        dataType: 'jsonp',
        jsonpCallback: 'get_wx_config',
        cache: true,
        success: function (data) {
            // 初始化微信接口
            wx.config({
                debug: false,
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'getLocation'
                ]
            });
            wx.ready(function () {
                wx.onMenuShareTimeline(Window.wxObj);
                wx.onMenuShareAppMessage(Window.wxObj);
                wx.onMenuShareQQ(Window.wxObj);
                wx.onMenuShareWeibo(Window.wxObj);
                wx.onMenuShareQZone(Window.wxObj);
                
                callback();
            });
        },
        error: function() {
            fail();
        }
    });
}

/* 通过微信接口定位 */
function getPosition() {
    var that = this;

    // 加载依赖
    Util.loadScript('//webapi.amap.com/maps?v=1.3&key=74dd8bc2bb2ce0e0938a376bef7bcc2d&plugin=AMap.Geocoder&callback=gaodeApiCallback', () => {
        
    });
}
window.gaodeApiCallback = function() {
    wx.getLocation({
        type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
            lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。

            // 取城市编码
            getCity();
        },
        fail: function() {
            fail();
        }
    });
};

/* 通过高德API取城市Code */
function getCity() {
    var lnglatXY = [lng, lat];
    //逆地理编码

    if(!AMap || !AMap.Geocoder){
        fail();
    }

    var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
    });
    geocoder.getAddress(lnglatXY, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
            cityCode = result.regeocode.addressComponent.citycode, // 这里取到的是地图的城市编码，需要转换成mdm的城市编码
            cityName = result.regeocode.addressComponent.city;

            // 取小店编码
            getStore();
        }
        else {
            fail();
        }
    });
}

/* 根据定位取小店信息 */
function getStore() {
    $.ajax({
        url: domains.poi + '/cmwsmdm-web/poi/locate.do',
        data: {
            lng: lng,
            lat: lat,
            cityCode: cityCode,
            cityCodeType: 'GAODE'
        },
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'getStore',
        cache: true,
        success: function(res) {
            if (res && res.code == '1' && res.data && res.data.poiInfoWhereCurrentCoordWithin) {
                var p = res.data.poiInfoWhereCurrentCoordWithin;
                cityCode = p.mdmCityCode; // 复写cityCode为mdm的城市编码
                storeCode = p.storeCode;
                storeLocation = p.storeLocation;
                storeName = p.storeName;
                poiId = p.poiId;
                poiName = p.poiName;
                areaId = p.areaId;

                // 成功获取兴趣点时保存到本地
                Util.setCookie('xd_cityCode', cityCode);
                Util.setCookie('xd_cityName', cityName);
                Util.setCookie('xd_storeLocation', storeLocation);
                Util.setCookie('xd_storeCode', storeCode);
                Util.setCookie('xd_storeName', storeName);
                Util.setCookie('xd_poiId', poiId);
                Util.setCookie('xd_poiName', poiName);
                Util.setCookie('xd_areaId', areaId || 0);

                ready();
            }
            else {
                fail();
            }
        },
        error: function() {
            fail();
        }
    });
}

function ready() {
    let data = {
        cityCode, cityName, storeCode, storeLocation, storeName, poiId, poiName, areaId
    }
    let lalp = {
        lat: lat,
        lng: lng
    }
    store.commit('setPosition', data);
    store.commit('setLalPosition',lalp)
    resolve(data);
}

function fail() {
    // router.push('/address/all/index')
    // store.commit('updateIsPosition', true)
    reject()
}


function probeAuthStatus2(hasLoginCallback, unLoginCallback, config) {
	if (typeof config == 'undefined') {
		if (typeof passport_config != 'undefined') {
			config = passport_config;
		} else {
			alert('You must define passport_config var.');
			return;
		}
	}
    $.ajax({
        url: config.base + 'authStatus',
        crossDomain: true,
        cache: false,
        dataType: 'jsonp',
        success: function (data) {
            if (data.hasLogin) {
            	var principal = data.principal;
                hasLoginCallback(principal);
            } else {
                unLoginCallback();
            }
        },
        error: function(a) {
            unLoginCallback();
        }
    });
}


export default (theStore) => {
    store = theStore;

    checkClient();
    pageRouter();
    setPassport();

    // 登录验证
    probeAuthStatus2(function(a){
        // 尝试读取URL参数中的兴趣点信息
        cityCode = Util.getUrlParam('cityCode'),
        cityName = Util.getUrlParam('cityName'),
        storeLocation = Util.getUrlParam('storeLocation'),
        storeCode = Util.getUrlParam('storeCode'),
        storeName = Util.getUrlParam('storeName'),
        poiId = Util.getUrlParam('poiId'),
        poiName = Util.getUrlParam('poiName'),
        areaId = Util.getUrlParam('areaId');

        // 尝试读取本地的兴趣点信息
        if (!cityCode || !cityName || !storeLocation || !storeCode || !storeName || !poiId || !poiName || !areaId) {
            cityCode = Util.getCookie('xd_cityCode'),
            cityName = Util.getCookie('xd_cityName'),
            storeLocation = Util.getCookie('xd_storeLocation'),
            storeCode = Util.getCookie('xd_storeCode'),
            storeName = Util.getCookie('xd_storeName'),
            poiId = Util.getCookie('xd_poiId'),
            poiName = Util.getCookie('xd_poiName'),
            areaId = Util.getCookie('xd_areaId');
        }
        if (cityCode && cityName && storeLocation && storeCode && storeName && poiId && poiName && areaId) {
            if (client.weixin) {
                initWeixin(function() {
                    ready();
                });
            }
            else {
                ready();
            }
        }
        else {
            if (client.weixin) {
                initWeixin(function() {
                    getPosition();
                });
            }
            else {
                fail();
            }
        }
    }, function() {
        Util.wxLogin();
    });

    return new Promise((res, rej) => {
        resolve = res;
        reject = rej;
    });
}
